<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>test</title>
</head>
<body>
<p>实体编码用来解决两件事情：1.代替html中的保留字符 2.表示特殊的字符</p>
<p>需要编码的html实体通常有空格, 大于号, 小于号, 单引号, 双引号,逻辑与 </p>
  <br>
  &lt;a href="#"&gt;test&lt;/a&gt;
  <a href="#">test</a>
  <!-- <input value="HTML转义字符&quot;(& q u o t ;)-OK" type="button" onclick="alert(&quot;OK&quot;);" /><br /> -->
  <script>
    var htmlUtil = {
      encodeHtml: function(html) {
        if(!html) return '';
        var s = html.replace(/&/g, '&amp;');
            s = s.replace(/</g, '&lt;');
            s = s.replace(/>/g, '&gt;');
            s = s.replace(/ /g, '&nbsp;');
            s = s.replace(/"/g, '&quot;');
            s = s.replace(/'/g, '&#39;');
        return s;
      },
      decodeHtml: function(str) {
        var s = "";
        if(str.length == 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, '<');
        s = s.replace(/&gt;/g, '>');
        s = s.replace(/&nbsp;/g, ' ');
        s = s.replace(/&quot;/g, '"');
        s = s.replace(/&#39;/g, '\'');
        return s;
      }
  };

  var a = '<p a="liu" b=\'abc\'>a bc</p>'; 
  console.log(htmlUtil.encodeHtml(a));
  console.log(htmlUtil.decodeHtml('&lt;p&nbsp;a=&quot;liu&quot;&nbsp;b=&#39;abc&#39;&gt;a&nbsp;bc&lt;/p&gt;'));
  </script>
</body>
</html>